require('JSON');
var so = require('socket.io');
var audioManager = require('./audioManager')();
var parseCookie = require('connect').utils.parseCookie;
var WebSocketServer = require('ws').Server;


module.exports = function(app, sessionStore) {
	var ws = new WebSocketServer({ server: app });
	var clientCount = 0;
	CLIENTS = { };//eventuel nicht global
	
	

	
	ws.on("connection", function(socket) {
		CLIENTS[++clientCount] = socket;
		socket.id = clientCount;
		emit = function(name, data){
			var msg = {
				msg: name,
				body: data
			};
			socket.send(JSON.stringify(msg));
		}
		console.log("user %s connected", socket.id);
		var controller = require('./socketController');

		socket.on('message', function(data, flags) {
			//flags.binary will be set if a binary data is received
			//flags.masked will be set if the data was masked
			//dispatch message
			if(typeof data == 'string'){
				data = JSON.parse(data);
				controller[data.msg](data.body, socket);
			}
		});
		socket.on("close", function(e) {
			console.log("user %s disconnects code %s", socket.id, e);
			delete CLIENTS[this.id];
		});
		socket.on("error",function(err){
			console.error(err);
		});
	});

	
	return {
		//
	};
}